<template>
  <div class="form-container">

    <el-form
      ref="editOperForm"
      :model="editOperForm"
      :rules="editOperFormRules"
      label-width="120px"
      size="small"
    >
      <el-form-item label="标题：" prop="title">
        <el-input v-model="editOperForm.title" placeholder="标题" />
      </el-form-item>
      <el-form-item label="心情：" prop="mood">
        <el-rate
          v-model="editOperForm.mood"
          style="line-height: 2;"
        />
      </el-form-item>
      <el-form-item label="日期：" prop="date">
        <el-date-picker
          v-model="editOperForm.date"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="日记内容：" prop="content">
        <tinymce v-model="editOperForm.content" :width="800" :height="400" />
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button size="medium" @click="back()">返回</el-button>
        <el-button type="primary" size="medium" @click="handleSaveDiary">保存日记</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import {
  updateById,
  create,
  getById
} from '@/api/life/diary'

import Tinymce from '@/components/Tinymce'

export default {
  name: 'AddDiary',
  components: { Tinymce },
  props: {
    isAdd: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editOperForm: {},
      editOperFormRules: {
        title: [{ required: true, trigger: 'blur', message: '请填写标题' }],
        date: [{ required: true, trigger: 'blur', message: '请选择日期' }],
        mood: [{ required: true, trigger: 'blur', message: '请选择心情' }],
        content: [{ required: true, trigger: 'blur', message: '请填写内容' }]
      }

    }
  },
  created() {
    if (!this.isAdd) {
      getById(this.$route.query.id).then(res => {
        const { id, date, content, title, mood } = res.data
        this.editOperForm = {
          id,
          date,
          content,
          title,
          mood
        }
      })
    }
  },
  methods: {
    handleSaveDiary() {
      this.$refs.editOperForm.validate(valid => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const params = Object.assign({}, this.editOperForm)

            if (this.isAdd) {
              create(params).then(_ => {
                this.$message.success('保存日记成功!')
                this.back()
              })
            } else {
              updateById(params.id, params).then(_ => {
                this.$message.success('修改日记成功！')
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    back() {
      this.$router.push({
        name: 'Diary'
      })
    }
  }
}
</script>

<style scoped>

</style>
